<script setup>
import {inject, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const $http = inject("$axios");
const $encode = inject("$qs");

const user = reactive({
  userId:'',
  userPwd:''
})
//设定输入的规则
const rules = reactive({
  name: [
    { required: true, message: '请首先输入用户名', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请首先输入密码',
      trigger: 'blur',
    }
  ],
});

const loginForm = ref(null);

let userInf = reactive({
  userId:"",
  name:"",
  password:"",
  sex:"",
  age:"",
  phone:"",
  email:"",
  job:""
});

function login() {
  $http.post("http://localhost:8088/api/user/login",
      //验证用户输入
      $encode.stringify({
        id: user.userId,
        pwd: user.userPwd
      })
  ).then(res => {
    userInf = res.data;
    //若登录失败
    if (userInf == '' || userInf == null || userInf == undefined){
      ElMessage.error('你的用户名或密码错误！');
    }else{
      router.push('/function');
      ElMessage.success('登录成功！');
    }
  }).catch(err => {
    ElMessage.error('登录失败！');
  })
}

function reset() {
  user.userId = "";
  user.userPwd = "";
}

function Register() {
  router.push('/register');
}

</script>

<template>
  <el-form ref="loginForm" :model="user" :rules="rules" label-width="auto">
    <el-form-item label="用户名" prop="name">
      <el-input type="text" v-model="user.userId" placeholder="请输入你的用户名"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="user.userPwd" placeholder="请输入你的密码"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" round @click="login">登录</el-button>
      <el-button type="danger" round @click="reset">重置</el-button>
      <el-button type="primary" round @click="Register">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>